package com.my.lab.receiver;

import java.util.HashMap;

import com.my.lab.activity.WifiActivity;
import com.my.lab.service.WlanService;
import com.my.lab.util.ConfigConstant;
import com.my.lab.util.WifiUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

public class WifiChangeReceiver extends BroadcastReceiver {
    private static final String TAG = "WifiChangeReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        WifiUtil wifiUtil = new WifiUtil(context);
        if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            int wifi_state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            Log.d(TAG, "wifi_state_change>>new state:" + wifi_state);
        } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            String bssId = intent.getExtras().getString(WifiManager.EXTRA_BSSID);
            Log.d(TAG, "network_state_change>>netwokinfo:" + info.getSubtypeName() + ",bssid:" + bssId);
            if(wifiUtil.getSSID().equals("NULL")) {
                context.startService(new Intent(context, WlanService.class));
            }
        } else if (intent.getAction().equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
            boolean flag = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
            Log.d(TAG, "Wi-Fi硬件和当前接入点之间的连接状态改变:" + flag);
            if (flag) {
                HashMap<String, Integer> infoMap = wifiUtil.getScanResult();
                if(infoMap.get(ConfigConstant.alis) != null && infoMap.get(ConfigConstant.alis) > 3) {
                    boolean result = wifiUtil.addNetwork(3, ConfigConstant.alis, ConfigConstant.psw);
                    Toast.makeText(context, "添加网络:"+result, Toast.LENGTH_SHORT).show();
                } else {
                    context.startService(new Intent(context, WlanService.class));
                }
            }
        } else if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
            Log.d(TAG, "wifi single strength change");
        }
    }
}
